use salvo::{async_trait, writing::Json, Depot, Request, Response, Writer};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct R<T> {
    flag: bool,
    code: i32,
    msg: String,
    data: Option<T>,
}

impl<T: Serialize> R<T> {
    /// 快速成功
    pub fn ok(data: T) -> Self {
        R {
            flag: true,
            code: 200,
            msg: "success".into(),
            data: Some(data),
        }
    }

    /// 快速失败
    pub fn err(code: i32, msg: impl Into<String>) -> Self {
        R {
            flag: false,
            code,
            msg: msg.into(),
            data: None,
        }
    }
}


#[async_trait]
impl<T> Writer for R<T>
where
    T: Serialize + Send + Sync + 'static,
{
    async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
        res.render(Json(self));
    }
}